"""操作系统环境监测"""

import os
import pwd
import psutil
import platform
import threading
import grp, json
import subprocess
from src.db import dbm, dbs
from src.core.log import log
from src.core.variables.info import sof
from sqlalchemy.orm import scoped_session
from src.core.variables.constant import CONF
from src.core.nodes.certification import Cert
from src.core.variables.info import FUNCTIONS
from src.core.variables.temp import MIDDLEWARE
from src.apps.middleware.java.manage import Java
from src.core.variables.function import CREATE_ID
from src.apps.middleware.nginx.manage import Nginx
from src.apps.middleware.unzip.manage import Unzip


def env_monitoring():
    t: bool = False
    # 校验运行用户是否是root
    if (
        pwd.getpwuid(os.getuid()).pw_name != "root"
        or grp.getgrgid(os.getgid()).gr_name != "root"
    ):
        log.CRITICAL("请使用root用户运行！")
    # 校验编译工具
    def check_build_tools():
        """校验编译工具是否存在"""
        missing_tools = []
        for tool in ["gcc", "make", "pkg-config"]:
            try:
                subprocess.run(
                    [tool, "--version"],
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                )
            except FileNotFoundError:
                missing_tools.append(tool)
        if not missing_tools:
            sof.c_compile = True
        return missing_tools

    missing_tools = check_build_tools()
    if sof.c_compile:

        def nginx_init():
            MIDDLEWARE.NGINX = Nginx()

        def unzip_init():
            MIDDLEWARE.UNZIP = Unzip()

        threading.Thread(target=nginx_init, name="fm_nginx").start()
        threading.Thread(target=unzip_init, name="fm_unzip").start()
        threading.Thread(target=Java, name="fm_java").start()
        t = True
    else:
        log.ERROR(f"缺少编译工具: {' '.join(missing_tools)}")
    if t:
        # 加载功能状态
        with dbm.get("sys_default") as db_session:
            db_session: scoped_session
            db_result = db_session.query(dbs.sys_default.Function).all()
            for i in db_result:
                if i.name in FUNCTIONS and i.status == "enable":
                    setattr(sof, i.name, True)
    if not t:
        log.CRITICAL("环境监测不通过...")


def init_data():
    # 初始化本机节点数据
    with dbm.get("sys_default") as db_session:
        db_session: scoped_session
        db_result = (
            db_session.query(dbs.sys_default.Node)
            .filter(dbs.sys_default.Node.host == "localhost")
            .all()
        )
        if len(db_result) == 0:
            db_session.add(
                dbs.sys_default.Node(
                    node_id=CREATE_ID(),
                    host="localhost",
                    ip=CONF.LOCAL_IP,
                    port=CONF.LOCAL_PORT,
                    status="running",
                    certificate="",
                    os_type=platform.system(),
                    os_version=platform.release(),
                    kernel_version=platform.release(),
                    cpu_model=platform.processor(),
                    cpu_cores=os.cpu_count(),
                    cpu_instruction_set=platform.machine(),
                    mem_size=psutil.virtual_memory().total,
                    disk_info=psutil.disk_usage("/").total,
                )
            )
        elif len(db_result) > 1:
            log.CRITICAL(f"数据库中存在多个当前节点的数据！请检查数据库！")
        if dbm.commit(db_session):
            log.INFO(f"初始化本节点数据成功！")
        # 初始化绑定信息
        cert = Cert()
        bind_info = {"certificate": json.dumps(cert.create_certificate())} 
        db_session.query(dbs.sys_default.Node).filter(
            dbs.sys_default.Node.host == "localhost"
        ).update(bind_info)
        if dbm.commit(db_session):
            log.INFO(f"创建绑定信息证书成功！")
